package com.qyl.deguru.controller.admin;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qyl.deguru.common.PageConstant;
import com.qyl.deguru.common.PageModel;
import com.qyl.deguru.dto.User;
import com.qyl.deguru.service.UserService;
import com.qyl.deguru.service.impl.UserServiceImpl;

@Controller
@RequestMapping("/admin/user")
public class AdminUserController {
	
	private UserService userService= new UserServiceImpl();

	@RequestMapping("/toUserList")
	public String toUserList(ModelMap map,User user,String pageIndex) {	
		/*
		 * 调用service用户列表
		 */
		PageModel pageModel=new PageModel();
		if(null!=pageIndex && pageIndex!=""){
			pageModel.setPageIndex(Integer.parseInt(pageIndex));
		}else{
			pageModel.setPageIndex(0);
		}
		pageModel.setPageSize(2);
		int recordCount=userService.getCountByUser(user);
		pageModel.setRecordCount(recordCount);
		List<User> users= userService.getUsers(user,pageModel);
		
		/*
		 * 放到request域里面
		 */
		map.addAttribute("users",users);
		map.addAttribute("user", user);
		map.addAttribute("pageModel", pageModel);
	 	return "user/userList";
	} 
	
	/*
	 * 删除用户数据
	 */
	@RequestMapping("/delUser")
	public String delUser(int id,ModelMap map){
		int count=userService.delUserById(id);
		if(count>0){
			map.put(PageConstant.TIP, "删除成功");
		}else{
			map.put(PageConstant.TIP, "删除失败");
		}
		return "forward:toUserList";
	}
	/*
	 * 批量删除
	 */
	@RequestMapping("/delBatchUsers")
	public String delBatchUsers(int [] ids,ModelMap map){
		int count=userService.delBatchUsers(ids);
		if(count>0){
			map.put(PageConstant.TIP, "删除成功");
		}else{
			map.put(PageConstant.TIP, "删除失败");
		}
		return "forward:toUserList";
	}
	/*
	 * 跳到增加用户界面
	 */
	@RequestMapping("/toAddUser")
	public String toAddUser(){
		return "user/userAdd";
	}
	/*
	 * 新增用户
	 */
	@RequestMapping("/add")
	public String addUser(ModelMap map,User user){
//		int count=UserService.addUser(user);
		user.setCreate_date(new Date());
		int count = userService.addUser(user);
		if(count>0){
			map.put(PageConstant.TIP, "添加成功");
		}else{
			map.put(PageConstant.TIP, "添加失败");
		}
		return "user/userAdd";
	}
	@RequestMapping("/toUserUpdate")
	public String toUserUpdate(ModelMap map,String id){
		/*
		 * 调用service层方法
		 */
		User user = userService.getUserById(id);
		/*
		 * 加入缓存
		 */
		map.addAttribute("updateUser", user);
		
		return "user/userUpdate";
	}
	/*
	 * 修改用户数据
	 */
	@RequestMapping("/updateUser")
	public String updateUser(User user,Map<String,String> map){
		int count=userService.updateUser(user);
		if(count>0){
			map.put(PageConstant.TIP, "更新成功");
		}else{
			map.put(PageConstant.TIP, "更新失败");
		}
		return "forward:toUserUpdate";
	}
	
}